<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>BrowserRouter的原理</title>
        <style>
            #result {
                height: 300px;
                width: 400px;
                border: solid 1px #666;
            }
        </style>
    </head>
    <body>
        <a href="/home">Home</a>
        <a href="/about">About</a>
        <hr />

        <div id="result"></div>

        <script>
            //获取 a 元素
            let links = document.querySelectorAll('a');
            //绑定事件
            links.forEach(a => {
                a.addEventListener('click', function(e){
                    //阻止默认行为
                    e.preventDefault();
                    //页面不刷新的情况下, 修改网页的 URL   history.pushState
                    history.pushState({id: 100}, '测试', e.target.href);
                    //根据 url 改变内容
                    switch(location.pathname){
                        case '/home':
                            result.innerHTML = 'HOME HOME HOME';
                            break;
                        case '/about':
                            result.innerHTML = 'ABOUT ABOUT ABOUT';
                            break;
                        default:
                            result.innerHTML = '404 Not Found';
                            break;
                    }

                });
            });

            window.addEventListener('popstate', function(){
                //更新 result 元素中的内容
                switch(location.pathname){
                    case '/home':
                        result.innerHTML = 'HOME HOME HOME';
                        break;
                    case '/about':
                        result.innerHTML = 'ABOUT ABOUT ABOUT';
                        break;
                    default:
                        result.innerHTML = '404 Not Found';
                        break;
                }
            });

        </script>
    </body>
</html>
